<template>
    <div
        class="zd-tabs"
        ref="zdTabs"
    >
        <div
            v-for="item in tabList"
            :key="item.value"
            class="zd-tabs__item"
            :class="{'active': active === item.value}"
            @click="handleClickTab(item.value, $event)"
        >
            {{ item.label }}
        </div>
        <div
            class="zd-tabs__active-bar"
            :style="{transform: `translateX(${activeBarLeft}px)`, width: `${activeBarWidth}px`}"
            v-if="show"
        />
    </div>
</template>

<script>
export default {
    name: "ZdTabs",
    props: {
        tabList: {
            type: Array,
            required: true
        },
        value: {
            type: null,
            default: ''
        }
    },
    model: {
        prop: 'value',
        event: 'change'
    },
    computed: {
        active: {
            get() {
                return this.value;
            },
            set(val) {
                this.$emit('change', val);
            }
        }
    },
    data() {
        return {
            activeBarLeft: 0,
            activeBarWidth: 0,
            show: false
        };
    },
    mounted() {
        this.$nextTick(() => {
            this.activeBarWidth = this.$refs.zdTabs.querySelector('.zd-tabs__item.active').offsetWidth - 32;
            this.activeBarLeft = this.$refs.zdTabs.querySelector('.zd-tabs__item.active').offsetLeft;
            this.show = true;
        });
    },
    methods: {
        /**
         * 点击tab
         * @param val
         * @param $event
         */
        handleClickTab(val, $event) {
            if(val === this.value) return false;
            this.active = val;
            this.activeBarLeft = $event.target.offsetLeft;
            this.activeBarWidth = $event.target.offsetWidth - 32;
        }
    }
};
</script>

<style scoped lang="less">
.zd-tabs {
    display: flex;
    align-items: center;
    height: 55px;
    border-bottom: 1px solid #EBEEF5;
    user-select: none;
    position: relative;
    &__item {
        height: 100%;
        display: flex;
        align-items: center;
        padding: 0 16px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #666666;
        cursor: pointer;
        &.active {
            color: #20A0FF;
            font-weight: 500;
        }
    }
    &__active-bar {
        width: 84px;
        height: 2px;
        background: #20A0FF;
        position: absolute;
        left: 16px;
        bottom: 0;
        transition: transform .3s cubic-bezier(.645,.045,.355,1);
    }
}
</style>
